package com.jt.www.util;

import com.jt.www.enums.BaseEnum;
import com.jt.www.exception.BizException;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {

    private static final String name = "ACD";
    private static final String SYMBOLS = "0123456789";
    private static final Random RANDOM = new SecureRandom();
    private static final String splitStr = "\\.";
    private static volatile Long timeStamp = 0L;

    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("127.0.0.1".equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ip = inet.getHostAddress();
            }
        }
        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    /**
     * 把字符串IP转换成long
     *
     * @param ipStr 字符串IP
     * @return IP对应的long值
     */
    public static long ip2Long(String ipStr) {
        String[] ip = ipStr.split("\\.");
        return (Long.valueOf(ip[0]) << 24) + (Long.valueOf(ip[1]) << 16)
                + (Long.valueOf(ip[2]) << 8) + Long.valueOf(ip[3]);
    }

    /**
     * 把IP的long值转换成字符串
     *
     * @param ipLong IP的long值
     * @return long值对应的字符串
     */
    public static String long2Ip(long ipLong) {
        StringBuilder ip = new StringBuilder();
        ip.append(ipLong >>> 24).append(".");
        ip.append((ipLong >>> 16) & 0xFF).append(".");
        ip.append((ipLong >>> 8) & 0xFF).append(".");
        ip.append(ipLong & 0xFF);
        return ip.toString();
    }

    /**
     * 创建不重复的序列号，服务重启可能会导致这个算法失效
     *
     * @return
     */
    public static String createAcdPreID(String shortName) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(shortName);
        stringBuilder.append(DateUtils.todayStr());
        stringBuilder.append(getNonce_str());
        return stringBuilder.toString();
    }

    /**
     * 获取长度为 6 的随机数字
     *
     * @return 随机数字
     * @date 修改日志：由 space 创建于 2018-8-2 下午2:43:51
     */
    public static String getNonce_str() {
        // 如果需要4位，那 new char[4] 即可，其他位数同理可得
        char[] nonceChars = new char[4];

        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }

        return new String(nonceChars);
    }

    /**
     * 公用枚举类code msg转换的方法
     *
     * @param baseEnums 枚举类父接口
     * @param code      枚举类定义的code值
     * @return
     */
    public static String getEnumMsgByCode(BaseEnum[] baseEnums, int code) {
        BaseEnum activityTypeEnum = null;
        for (BaseEnum ae : baseEnums) {
            if (ae.getCode().equals(code)) {
                activityTypeEnum = ae;
                break;
            }
        }
        return activityTypeEnum == null ? null : activityTypeEnum.getMsg();
    }

    public static boolean isMobiPhoneNum(String regex, String telNum) {
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(telNum);
        return m.matches();
    }

    public static void main(String[] args) {
        String v1 = "1.0.0";
        String v2 = "1.0.1";
        String v3 = "1.1.0";
        String v4 = "1.0.1";

        String v5 = "1.1.2";
        String v6 = "1.1.2";
        System.out.println(compareVersion(v1, v2));
        System.out.println(compareVersion(v3, v4));
        System.out.println(compareVersion(v5, v6));
    }

    public static String getUUID() {
        String s = UUID.randomUUID().toString();
        //去掉“-”符号
        return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
    }

    /**
     * 获得指定数目的UUID
     *
     * @param number int 需要获得的UUID数量
     * @return String[] UUID数组
     */
    public static String[] getUUID(int number) {
        if (number < 1) {
            return null;
        }
        String[] ss = new String[number];
        for (int i = 0; i < number; i++) {
            ss[i] = getUUID();
        }
        return ss;
    }

    /**
     * 输入的字符是否是汉字
     *
     * @param a char
     * @return boolean
     */
    public static boolean isChinese(char a) {
        int v = (int) a;
        return (v >= 19968 && v <= 171941);
    }

    /**
     * 判断字符串中是否包含中文字符
     *
     * @param s
     * @return
     */
    public static boolean containsChinese(String s) {
        if (null == s || "".equals(s.trim())) {
            return false;
        }
        for (int i = 0; i < s.length(); i++) {
            if (isChinese(s.charAt(i))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断集合是否为空
     *
     * @param collection 集合
     * @return
     */
    public static Boolean isEmpty(Collection collection) {
        if (collection == null || collection.isEmpty()) {
            return true;
        }
        return false;
    }

    /**
     * 乱码转换
     *
     * @param str
     * @return
     */
    public static String converCode(String str) {
        String s = null;
        try {
            byte[] bytes = str.getBytes();
            s = new String(bytes, "utf-8");
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * ver1 > ver 2 return 1
     * ver1 equal 2 return 0
     * ver1 < ver 2 return -1
     *
     * @param ver1
     * @param ver2
     */
    public static int compareVersion(String ver1, String ver2) {
        String[] verSpl = ver1.split(splitStr);
        String[] verSp2 = ver2.split(splitStr);
        if (verSpl.length != verSp2.length) {
            throw new BizException("版本号比较，版本格式不一致: " + ver1 + "  " + ver2);
        }
        int length = verSpl.length;
        for (int i = 0; i < length; i++) {
            if (Integer.valueOf(verSpl[i]).compareTo(Integer.valueOf(verSp2[i])) > 0) {
                return 1;
            } else if (Integer.valueOf(verSpl[i]).compareTo(Integer.valueOf(verSp2[i])) == 0) {
                continue;
            } else {
                return -1;
            }
        }
        return 0;
    }

    /**
     * 将流转换为byte 数组
     *
     * @param inStream
     * @return
     */
    public static byte[] readStream(InputStream inStream) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        try {
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outStream.close();
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return outStream.toByteArray();
    }
}
